package cre.sample.test.bigdata;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * 固定数量的fork
 *
 * @Author penglai
 * @Date 2016/9/28.
 */
public class ForkTask1 extends RecursiveTask<List<ListenBean>> {

    public static final int THRESHOLD = 10000;

    private int start;
    private int end;
    private List<ListenBean> source;

    public ForkTask1(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public ForkTask1(int start, int end, List<ListenBean> source) {
        this.start = start;
        this.end = end;
        this.source = source;
    }

    /**
     * The main computation performed by this task.
     */
    @Override
    protected List<ListenBean> compute() {
        List<ListenBean> ret = new ArrayList<ListenBean>();
        boolean execute = (end - start) <= THRESHOLD;
        if (execute) {
            long t1 = System.currentTimeMillis();
            System.out.println(Thread.currentThread().getName() + " thread start ");
            for (int i = start; i < end; i++) {
                ret.add(source.get(i));
            }
            long t2 = System.currentTimeMillis();
            System.out.println(Thread.currentThread().getName() + " thread done " + (t2 - t1));
        } else {
            int middle = (end + start) / 2;
            ForkTask1 leftTask = new ForkTask1(start, middle, source);
            ForkTask1 rightTask = new ForkTask1(middle, end, source);
            // 执行子任务
            leftTask.fork();
            rightTask.fork();

            ret.addAll(leftTask.join());
            ret.addAll(rightTask.join());
        }
        return ret;
    }
}
